<?php
namespace Lidong\Weather;

use GuzzleHttp\Client;
use Lidong\Weathe\Exceptions\HttpException;
use Lidong\Weathe\Exceptions\InvalidArgumentException;

class Weather
{
    protected $key;
    protected $guzzleOptions = [];

    public function __construct(string $key)
    {
        $this->key = $key;
    }

    /*
     * @return GuzzleHttp\Client
     * */
    public function getHttpClient()
    {
        return new Client($this->guzzleOptions);
    }

    public function setGuzzleOptions(array $options)
    {
        $this->guzzleOptions = $options;
    }

    /*
     * get weather
     *
     * @param mixed $city
     * @param str $type
     * @param str $formal
     *
     * @return mixed result
     * */
    public function getWeather($city, string $type = 'base', string $formal = 'json')
    {
        $url = 'https://restapi.amap.com/v3/weather/weatherInfo';

        if(!\in_array(\strtolower($formal), ['xml','json'])) {
            throw new InvalidArgumentException('Invalid response formal: '.$formal);
        }

        if(!\in_array(\strtolower($type),['base','all'])) {
            throw new InvalidArgumentException('Invalid type value(base/all): '.$type);
        }

        $query = array_filter([
            'key' => $this->key,
            'city' => $city,
            'output' => $formal,
            'extensions' => $type
        ]);

        try{
            $response = $this->getHttpClient()->get($url,[
                'query' => $query
            ])->getBody()->getContents();

            return 'json' === $formal ? \json_decode($response,true) : $response;
        } catch (\Exception $e){
            throw new HttpException($e->getMessage(), $e->getCode(), $e);
        }
    }


}

